<template>
  <div class='container'>
    <!-- 弹窗 -->
        <el-dialog :title="dialogTitle" :visible="showdialog" width="400px" @close="cancel">
          <el-form :model="newForm" :rules="rules" ref="newForm">
            <el-form-item  label="所属学科" prop="subjectID">
              <el-select v-if="!$route.query.id" v-model="newForm.subjectID" placeholder="请选择"  style="width:280px">
                 <el-option v-for="item in list" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="标签名称" prop="tagName">
              <el-input v-model="newForm.tagName" placeholder="请输入标签名称" style="width:280px"/>
            </el-form-item>
          </el-form>
          <el-row type="flex" justify="end">
              <el-button size="middle" @click="cancel">取消</el-button>
              <el-button type="primary" size="middle" @click="okBtn">确定</el-button>
          </el-row>
        </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { add as addDire, detail, update } from '@/api/hmmm/tags'

export default {
  props: {
    showdialog: {
      type: Boolean,
      default: false
    },
    subjectID: {
      type: Number,
      default: null
    }
  },
  computed: {
    dialogTitle () {
      return this.newForm.id ? '编辑标签' : '新增标签'
    }
  },
  data () {
    return {
      list: [], // 学科列表
      newForm: { // 弹窗表单
        subjectID: this.$route.query.id || null,
        tagName: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科名称', trigger: 'blur' }],
        tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 取消
    cancel () {
      this.newForm = {
        subjectID: null,
        tagName: null
      }
      this.$emit('update:showdialog', false)
    },
    // 新增标签&&修改标签提交
    okBtn () {
      this.$refs.newForm.validate().then(async (result) => {
        if (this.newForm.id) { // id存在则是修改标签
          await update(this.newForm)
        } else { // id不存在则是新增标签
          await addDire(this.newForm)
        }
        this.$message.success(this.dialogTitle + '成功!')
        this.cancel()
        this.$emit('updateList')
      }).catch((err) => {
        console.log(err)
      })
    },
    // 初始化学科列表
    async simple () {
      const { data } = await simple()
      this.list = data
    },
    // 初始化弹窗信息
    async getForm (id) {
      const { data } = await detail({ id })
      this.newForm = data
    }
  }
}
</script>

<style scoped lang='less'></style>
